<template>
  <!-- 点击开始播放 -->
  <span class="MC_iconfont MC_icon-qiyong-kaishi" v-if="!STATE.isPlay" @click.stop="onPlayOrPause('play')"></span>
  <!-- 点击暂停播放 -->
  <span class="MC_iconfont MC_icon-qiyong-zanting" v-else @click.stop="onPlayOrPause('pause')"></span>
</template>

<script lang="ts">
import { defineComponent, nextTick, reactive, watch, onMounted, onBeforeUnmount, onDeactivated } from 'vue'
import { globalModule } from '@/common/store/modules/global'
import bus from '@/common/utils/bus'
export default defineComponent({
  name: 'audioOperate',
  emits: ['onAudioClick'],
  props: {
    row: {
      type: Object,
      default: () => {
        return {
          url: '', // 当前的音频地址
          isplay: false, // 当前的播放状态，可结合_id使用，列表类型的必传
          _id: '' // 当前录音播放的标识，用于满足列表中多个录音播放的，点击某一个，其他要重置的情况
        }
      }
    }
  },
  components: {},
  setup(props, { emit }) {
    const GLOBAL = globalModule()
    const STATE = reactive({
      isPlay: props.row.isPlay || false, // 控制播放按钮的状态
      url: props.row.url || '', // 播放的录音地址
      _id: props.row._id || ''
    })
    watch(
      () => props.row,
      (newVal: any) => {
        STATE.isPlay = newVal.isplay
        STATE.url = newVal.url
        STATE._id = newVal._id
      },
      { immediate: true }
    )
    const onPlayOrPause = (type: string) => {
      STATE.isPlay = !STATE.isPlay // 播放状态取反
      emit('onAudioClick', { _id: props.row._id, isplay: STATE.isPlay }) // 用于列表类型的重置其他兄弟的状态
      const audioNode = document.getElementById('mc_audio_hide') as HTMLVideoElement
      if (type === 'play' && audioNode) {
        // 播放录音
        audioNode.setAttribute('src', STATE.url)
        GLOBAL.setAudioObj({ audioUrl: STATE.url })
      }
      nextTick(() => {
        // 开始或者是暂停录音，可以父级直接调用
        if (audioNode) {
          if (type === 'play') {
            // 播放录音
            audioNode.play()
          } else {
            // 暂停录音
            audioNode.pause()
          }
        }
      })
    }
    const restStatus = () => {
      // 重置所有状态（icon重置成待播放，录音暂停）
      GLOBAL.setAudioObj({ currentId: '', audioUrl: '' })
      STATE.isPlay = false
      const audioNode = document.getElementById('mc_audio_hide') as HTMLVideoElement
      if (audioNode && audioNode.currentSrc) {
        audioNode.pause()
      }
    }

    onMounted(async () => {
      bus.on('restAudioStatus', () => {
        // 事件总线，重置audio
        restStatus()
      })
    })

    onBeforeUnmount(() => {
      // 组件销毁时，清除事件总线
      restStatus()
      bus.off('restAudioStatus')
    })
    onDeactivated(() => {
      // 组件没有被激活的时候，重置 eg: 播放录音中途切换到别的模块
      restStatus()
    })
    return { STATE, onPlayOrPause }
  }
})
</script>

<style lang="stylus" scoped>
.MC_iconfont
  font-size 20px
  color var(--mc-main-color)
</style>
